import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/views/report/model/leads_operation_report.dart';
import 'package:yuan_hang_app/views/report/widget/empty_widget.dart';

import '../../res/w_colors.dart';
import '../../res/w_dimens.dart';
import '../../widget/custom_search.dart';
import '../../widget/sort_content.dart';
import '../../widget/w_line.dart';
import '../../widget/w_popup_window.dart';
import '../../widget/w_text.dart';

class OperationReportPage extends StatefulWidget {
  const OperationReportPage({super.key});

  @override
  BaseState<OperationReportPage> createState() => OperationReportPageState();
}

class OperationReportPageState extends BaseState<OperationReportPage> {
  Map sortParams = {};

  Map<String, dynamic> queryParams = {};
  List<LeadsOperationReport> dataList = [];

  Future<Null> _refresh() async {
    showLoading();
    fetchDataList();
  }

  @override
  void initState() {
    super.initState();

    queryParams["startTime"] = DateUtil.formatDate(DateTime(DateTime.now().year,DateTime.now().month,1), format: DateFormats.y_mo_d);
    queryParams["endTime"] = DateUtil.formatDate(DateTime(DateTime.now().year,DateTime.now().month + 1,0), format: DateFormats.y_mo_d);

    sortParams["startTime"] = queryParams["startTime"];
    sortParams["endTime"] = queryParams["endTime"];

    fetchDataList();
  }

  void fetchDataList() {
    dataList = [];
    HttpUtils()
        .post(Api.getClueOperationReport, data: queryParams)
        .then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        if (value.data != null) {
          List data = value.data ?? [];
          List<LeadsOperationReport> list =
              data.map((item) => LeadsOperationReport.fromJson(item)).toList();
          setState(() {
            dataList = list;
          });
        }
      }
    });
  }

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
      title: "线索运营报表",
      rightWidget: GestureDetector(
        onTap: () {
          WPopupWindow.showSort(
              context: context,
              sortType: SortType.LEADS_OPERATION_REPORT,
              sortParams: sortParams,
              onSelected: (Map params) {
                sortParams = params;
                params.forEach((key, value) {
                  queryParams[key] = value;
                  if (queryParams.containsKey(key) && value == null) {
                    queryParams.remove(key);
                  }
                });
                if (queryParams["startTime"] == null && queryParams["endTime"] == null) {
                  queryParams["startTime"] = DateUtil.formatDate(DateTime(DateTime.now().year,DateTime.now().month,1), format: DateFormats.y_mo_d);
                  queryParams["endTime"] = DateUtil.formatDate(DateTime(DateTime.now().year,DateTime.now().month + 1,0), format: DateFormats.y_mo_d);
                }
                showLoading();
                fetchDataList();
              });
        },
        child: Padding(
          padding: EdgeInsets.only(right: 10.px),
          child: WText(
            "筛选",
            style: TextStyle(
              color: WColors.primaryColor,
              fontSize: 14.px,
            ),
          ),
        ),
      ),
      child: Column(
        children: [
          Expanded(
            child: RefreshIndicator(
                onRefresh: _refresh,
                child: ListView.builder(
                  padding: EdgeInsets.only(top: 10.px),
                  itemBuilder: _listItem,
                  itemCount: dataList.length,
                )),
          ),
        ],
      ),
    );
  }

  Widget _listItem(context, index) {
    LeadsOperationReport item = dataList[index];

    return Container(
        decoration: BoxDecoration(boxShadow: [
          BoxShadow(
              color: WColors.CDFEFFB,
              offset: const Offset(0, 1),
              blurRadius: 3.px)
        ], borderRadius: BorderRadius.circular(10.px), color: Colors.white),
        margin: EdgeInsets.only(left: 10.px, right: 10.px, bottom: 10.px),
        padding: EdgeInsets.only(bottom: 10.px),
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(height: 10.px),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  WLine(
                    height: 16.px,
                    width: 4.px,
                    color: WColors.primaryColor,
                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 10.px),
                      child: WText(
                        item.title ?? "",
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: WDimens.tsLarge,
                            color: WColors.mainTextColor,
                            fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(
                height: 5.px,
              ),
              _itemRow("店面数量", item.shopNum ?? ""),
              _itemRow("线索数量", item.clueNum ?? ""),
              _itemRow("有效线索数量", item.validClueNum ?? ""),
              _itemRow("线索有效率", item.validRate ?? ""),
              _itemRow("试驾数量", item.testDriveNum ?? ""),
              _itemRow("试驾率", item.testDriveRate ?? ""),
              _itemRow("跟进逾期次数", item.followOverdueNum ?? ""),
              _itemRow("订单数量", item.orderNum ?? "", isLast: true),
            ]));
  }

  Widget _itemRow(dataTitle, data, {bool isLast = false}) {

    BoxDecoration leftDecoration = BoxDecoration(
        border: Border(
            left: BorderSide(color: WColors.CCCCCCC, width: 1.px),
            top: BorderSide(color: WColors.CCCCCCC, width: 1.px),
            right: BorderSide(color: WColors.CCCCCCC, width: 1.px)));
    BoxDecoration rightDecoration = BoxDecoration(
        border: Border(
            top: BorderSide(color: WColors.CCCCCCC, width: 1.px),
            right: BorderSide(color: WColors.CCCCCCC, width: 1.px)));
    if (isLast) {
      leftDecoration = BoxDecoration(
          border: Border.all(color: WColors.CCCCCCC, width: 1.px));
      rightDecoration = BoxDecoration(
          border: Border(
              bottom: BorderSide(color: WColors.CCCCCCC, width: 1.px),
              top: BorderSide(color: WColors.CCCCCCC, width: 1.px),
              right: BorderSide(color: WColors.CCCCCCC, width: 1.px)));
    }


    return Container(
      padding: EdgeInsets.symmetric(horizontal: 5.px),
      child: Row(
        children: [
          Expanded(
            flex: 3,
            child: Container(
              padding: EdgeInsets.only(left: 5.px),
              decoration: leftDecoration,
              child: WText(
                dataTitle,
                style: TextStyle(
                    fontSize: WDimens.tsMedium, color: WColors.mainTextColor),
              ),
            ),
          ),
          Expanded(
            flex: 2,
            child: Container(
              alignment: Alignment.center,
              decoration: rightDecoration,
              child: WText(
                data.toString(),
                style: TextStyle(
                    fontSize: WDimens.tsMedium, color: WColors.mainTextColor),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
